package com.atguigu.gulimall.search.thread;

import java.util.concurrent.*;

/**
 * @create: 2024/9/4
 * @author: gyhe10
 * @description: 多线程测试
 **/

public class ThreadTest {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        System.out.println("main...start...");

        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品图片信息");
            return "hello.jpg";
        }, threadPool);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品的属性信息");
                return "黑色 8 + 128";
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPool);

        CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品描述信息");
            return "华为";
        }, threadPool);

        CompletableFuture<Void> future = CompletableFuture.allOf(future01, future02, future03);

        try {
            future.get();
            System.out.println("任务一执行结果：" + future01.get());
            System.out.println("任务二执行结果：" + future02.get());
            System.out.println("任务三执行结果：" + future03.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("main...end...");
    }



    public void thread(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开启...");
        /**
         * 创建线程的 4 种方式
         * 1. 继承 Thread 类，重写 run()
         * 2. 实现 Runnable 接口，重写 run()
         * 3. 实现 Callable 接口，重写 call()
         * 4. 使用线程池
         */

        Future<Integer> submit = threadPool.submit(new Callable01());


        System.out.println("主线程结束...");
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Runnable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Callable01 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }


}
